package com.jifeng.api.crud.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jifeng.api.crud.entity.OrderEntity;
import com.jifeng.api.crud.service.OrderService;
import com.jifeng.api.utils.HttpUtils;
import com.jifeng.api.utils.PageUtils;
import com.jifeng.api.utils.Query;
import com.jifeng.api.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jifeng.api.crud.dao.VwDeviceUserDao;
import com.jifeng.api.crud.entity.VwDeviceUserEntity;
import com.jifeng.api.crud.service.VwDeviceUserService;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


@Service("vwDeviceUserService")
@Slf4j
public class VwDeviceUserServiceImpl extends ServiceImpl<VwDeviceUserDao, VwDeviceUserEntity> implements VwDeviceUserService {

    @Autowired
    OrderService orderService;

    public String getRequestUrl() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest().getRequestURI();
    }

    public HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

    @Override
    public R queryPage(Map<String, Object> params) {
        try {
            QueryWrapper<VwDeviceUserEntity> queryWrapper = new QueryWrapper<>();

            /**
             * 获取所传参数
             */
            String userName = Convert.toStr(params.get("userName"));
            String iot = Convert.toStr(params.get("ID"));
            String workState = Convert.toStr(params.get("workState"));
            String state = Convert.toStr(params.get("state"));
            String terminalId = Convert.toStr(params.get("terminalId"));
            String createTime = Convert.toStr(params.get("createTime"));

            /**
             * 解析token获取登录用户信息
             */
            Map<String, Object> userInfo = HttpUtils.getUserIdByToken(getRequest());
            if (userInfo == null) {
                log.warn("path：{}，errMsg：{}，cause：{}", getRequestUrl(), "获取token信息失败", "未知异常");
                return R.error("获取token信息失败");
            }

            /**
             * 校验所传户主名是否为空
             */
            if (!StrUtil.isEmpty(userName)) {

                /**
                 * 判断登录用户类型
                 */
                String userType = Convert.toStr(userInfo.get("type"));
                if (userType.equals("2")) {
                    String name = Convert.toStr(userInfo.get("name"));
                    queryWrapper.eq("name", name);
                } else if (userType.equals("1")) {
                    queryWrapper.like("name", userName);
                }
            }

            /**
             * 校验所传设备状态是否为空
             */
            if (!StrUtil.isEmpty(state)) {
                List<VwDeviceUserEntity> collect = null;
                List<VwDeviceUserEntity> deviceUserEntities = this.list();

                // 查询未使用的设备
                if (state.equals("0")) {
                    collect = deviceUserEntities.stream().filter(deviceUserEntity -> {
                        String terminalId1 = deviceUserEntity.getTerminalId();
                        Date revTime = deviceUserEntity.getRevTime();
                        int second = 0;
                        if (revTime != null) {
                            second = new Long(DateUtil.between(revTime, new Date(), DateUnit.SECOND)).intValue();
                        }
                        return (StrUtil.isEmpty(terminalId1) && deviceUserEntity.getOrderId() == null) || (!StrUtil.isEmpty(terminalId1) && second > 300);
                    }).collect(Collectors.toList());
                } else if (state.equals("1")) {
                    collect = deviceUserEntities.stream().filter(deviceUserEntity -> {
                        String terminalId1 = deviceUserEntity.getTerminalId();
                        Date revTime = deviceUserEntity.getRevTime();
                        int second = 0;
                        if (revTime != null) {
                            second = new Long(DateUtil.between(revTime, new Date(), DateUnit.SECOND)).intValue();
                        }
                        return (!StrUtil.isEmpty(terminalId1) && second <= 300);
                    }).collect(Collectors.toList());
                } else if (state.equals("2")) {
                    collect = deviceUserEntities.stream().filter(deviceUserEntity -> deviceUserEntity.getOrderId() != null).collect(Collectors.toList());
                } else {
                    log.warn("path：{}，errMsg：{}", getRequestUrl(), "state只能为0/1/2");
                    return R.error("state只能为0/1/2");
                }

                IPage<VwDeviceUserEntity> page = this.page(
                        new Query<VwDeviceUserEntity>().getPage(params),
                        queryWrapper
                );

                page.setRecords(collect);
                page.setTotal(collect.size());
                return R.ok().put("page", new PageUtils(page));
            }


            /**
             * 校验所传设备编号是否为空
             */
            if (!StrUtil.isEmpty(iot)) {
                queryWrapper.eq("IOT", iot);
            }

            /**
             * 校验所传工作状态是否为空
             */
            if (!StrUtil.isEmpty(workState)) {
                queryWrapper.eq("work_status", workState);
            }

            /**
             * 校验所传机柜编号是否为空
             */
            if (!StrUtil.isEmpty(terminalId)) {
                queryWrapper.eq("terminal_id", terminalId);
            }

            /**
             * 校验所传创建时间是否为空
             */
            if (!StrUtil.isEmpty(createTime)) {
                queryWrapper.like("create_time", createTime);
            }


            IPage<VwDeviceUserEntity> page = this.page(
                    new Query<VwDeviceUserEntity>().getPage(params),
                    queryWrapper
            );

            page.setRecords(page.getRecords().stream().map(vwDeviceUserEntity -> {
                String terminalId1 = vwDeviceUserEntity.getTerminalId();
                Long orderId = vwDeviceUserEntity.getOrderId();
                Date revTime = vwDeviceUserEntity.getRevTime();
                int second = 0;
                String deviceStatus = "";
                if (revTime != null) {
                    second = new Long(DateUtil.between(revTime, new Date(), DateUnit.SECOND)).intValue();
                }
                if ((StrUtil.isEmpty(terminalId1) && orderId == null) || (!StrUtil.isEmpty(terminalId1) && second > 300)) {
                    deviceStatus = "0";
                } else if (!StrUtil.isEmpty(terminalId1) && second <= 300) {
                    deviceStatus = "1";
                } else if (orderId != null) {
                    deviceStatus = "2";
                }

                vwDeviceUserEntity.setState(deviceStatus);
                return vwDeviceUserEntity;
            }).collect(Collectors.toList()));
            return R.ok().put("page", new PageUtils(page));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("path：{}，errMsg：{}", getRequestUrl(), e.getMessage());
            return R.sysError();
        }
    }
}